package com.bbx.taxi.client.Activity.Wallet;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bbx.androidapi.util.ToastUtil;
import com.bbx.api.sdk.model.comm.returns.line.Line;
import com.bbx.api.sdk.model.passanger.Return.CouponCount;
import com.bbx.taxi.client.Activity.Base.BaseBBXActivity;
import com.bbx.taxi.client.Adapter.PayAdapter;
import com.bbx.taxi.client.Bean.Wallect;
import com.bbx.taxi.client.R;
import com.bbx.taxi.client.Task.MyRechargeTask;
import com.bbx.taxi.client.Util.IsDataFail;
import com.bbx.taxi.client.Util.ListViewHeight;
import com.bbx.taxi.client.Util.RequestUtils;
import com.bbx.taxi.client.wxapi.WXPayEntryActivity;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 作者：严旭文 on 2016/12/28 13:52
 * 邮箱：420255048@qq.com
 * 充值
 */
public class RechargeActivity  extends BaseBBXActivity implements TextWatcher{
    @Bind(R.id.tv_balance)
    TextView tv_balance;
    @Bind(R.id.gridview)
    GridView gridview;
    @Bind(R.id.listview_pay)
    ListView listview_pay;
    @Bind(R.id.layout_clause)
    LinearLayout layout_clause;
    @Bind(R.id.et_inputamount)
    EditText et_inputamount;
    PayAdapter mPayAdapter;
    AmountAdapter mAmountAdapter;
    /** 支付列表 */
    private List<Map<String, String>> list_pay;
    /**推荐的充值金额列表*/
    List<Amount> list_amount;
    // 支付id,则为类型，0为银联
    private int pay_id = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_recharge);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initView() {
        setTitle(getString(R.string.recharge));
        et_inputamount.addTextChangedListener(this);
    }

    @Override
    protected void onResume() {
        RequestUtils.requesBalance(this);
        super.onResume();
    }

    @Override
    protected void initData() {
        initBalance();
        /*************************选择金额*********************************/
        list_amount=new ArrayList<>();
        int[] amount=new int[]{100,300,500,1000,2000,5000};
        for(int i=0;i<amount.length;i++){
            Amount mAmount=new Amount();
            mAmount.amount=amount[i];
            mAmount.extra=mAmount.amount/5;
            list_amount.add(mAmount);
        }
        mAmountAdapter=new AmountAdapter(list_amount);
        gridview.setAdapter(mAmountAdapter);
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                et_inputamount.setText("");
                mAmountAdapter.setSelector(position);
                mAmountAdapter.notifyDataSetChanged();
            }
        });
        ListViewHeight
                .seGridViewHeightBasedOnChildren(context, gridview, R.layout.item_recharge_amount);
        /*************************支付方式*********************************/
        onSetPayList();
        mPayAdapter = new PayAdapter(context, list_pay);
        listview_pay.setAdapter(mPayAdapter);
        ListViewHeight.setListViewHeightBasedOnChildren(listview_pay);
        listview_pay.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                pay_id = position;
                PayAdapter.ViewHolder vHollder = (PayAdapter.ViewHolder) view.getTag();
                if (!vHollder.cb_pay.isChecked()) {
                    vHollder.cb_pay.toggle();
                }
                for (int i = 0; i < list_pay.size(); i++) {
                    if (i == position) {
                        mPayAdapter.isSelected.put(i, true);
                    } else {
                        mPayAdapter.isSelected.put(i, false);
                    }
                }
                mPayAdapter.notifyDataSetInvalidated();
            }
        });
    }

    /**
     * 设置金额
     */
    public void initBalance(){
        if(Wallect.accountBalance==null){
            Wallect.accountBalance="0";
        }
        tv_balance.setText(Wallect.accountBalance);
    }
    /**
     * 设置支付列表
     */
    private void onSetPayList() {
        list_pay = new ArrayList<Map<String, String>>();
        Map<String, String> map = new HashMap<String, String>();
        // 支付宝
        map = new HashMap<String, String>();
        map.put(PayAdapter.TYPE, PayAdapter.TYPE_ALIPAY);
        map.put(PayAdapter.TEXT, getString(R.string.pay_way_alipay));
        map.put(PayAdapter.DISCOUNT, "0");
        list_pay.add(map);
        // 微信
        map = new HashMap<String, String>();
        map.put(PayAdapter.TYPE, PayAdapter.TYPE_WEIXIN);
        map.put(PayAdapter.TEXT, getString(R.string.pay_way_weixin));
        map.put(PayAdapter.DISCOUNT, "0");
        map.put(PayAdapter.AVAILABLE, WXPayEntryActivity
                .isWXAppInstalledAndSupported(context) ? "true" : "false");
        list_pay.add(map);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if(!s.toString().isEmpty()){
            mAmountAdapter.setSelector(-1);
            mAmountAdapter.notifyDataSetChanged();
        }
    }

    public class Amount{
        public int amount;//金额
        public int extra ;//额外送的金额
    }
    public class AmountAdapter extends BaseAdapter {
        List<Amount> list;
        int selector=-1;
        public AmountAdapter(List<Amount> list){
           this.list=list;
        }
        @Override
        public int getCount() {
            return list!=null?list.size():0;
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }
        public void setSelector(int selector){
            this.selector=selector;
        }
        public int getSelector(){return  selector;}

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewholder;
            if(convertView==null){
                LayoutInflater inflater=LayoutInflater.from(context);
                convertView=(View)inflater.inflate(R.layout.item_recharge_amount,null);
                viewholder=new ViewHolder();
                viewholder.tv_amount=(TextView)convertView.findViewById(R.id.tv_amount);
                viewholder.tv_extra=(TextView)convertView.findViewById(R.id.tv_extra);
                viewholder.layout=(LinearLayout)convertView.findViewById(R.id.layout);
                convertView.setTag(viewholder);
            }
            else viewholder=(ViewHolder)convertView.getTag();
            viewholder.tv_amount.setText(list.get(position).amount+"");
            viewholder.tv_extra.setText(list.get(position).extra+"");
            if(selector==position){
                viewholder. layout.setSelected(true);
                viewholder.tv_amount.setSelected(true);
                viewholder.tv_extra.setSelected(true);
            }else{
                viewholder. layout.setSelected(false);
                viewholder.tv_amount.setSelected(false);
                viewholder.tv_extra.setSelected(false);
            }
            return convertView;
        }
        public class ViewHolder{
            TextView tv_amount,tv_extra;
            LinearLayout layout;
        }
    }

    @Override
    @OnClick({R.id.layout_clause, R.id.btn_recharge})
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.layout_clause:
                ToastUtil.showToast(context,"充值协议");
                break;
            case R.id.btn_recharge:
                if(et_inputamount.getText().toString().isEmpty()&&mAmountAdapter.getSelector()<0){
                    ToastUtil.showToast(context,"请输入金额");
                }else{
                    if(!et_inputamount.getText().toString().isEmpty()){
                        onRecharge(et_inputamount.getText().toString());
                    }else if(mAmountAdapter.getSelector()<0){
                        onRecharge(list_amount.get(mAmountAdapter.getSelector()).amount+"");
                    }
                }
                break;
            default:
                super.onClick(v);
                break;
        }
    }
    @Override
    public void onNotifyData(DATA_STATUS data_status, DATA_TYPE data_type, int status, Object object) {
        switch (data_type) {
            case BALANCE:
                initBalance();
                break;
        }
        super.onNotifyData(data_status, data_type, status, object);
    }
    /**
     * @param amount
     * 开始充值
     */
    public void onRecharge(String amount){
        mAmountAdapter.setSelector(-1);
        mAmountAdapter.notifyDataSetChanged();
        et_inputamount.setText("");
        if (list_pay.get(pay_id).get(PayAdapter.TYPE)
                .equals(PayAdapter.TYPE_ALIPAY)) {
            RequestUtils.requesRecharge(context, MyRechargeTask.GATEWAY.alipay,amount);
        }else if (list_pay.get(pay_id).get(PayAdapter.TYPE)
                .equals(PayAdapter.TYPE_WEIXIN)) {
            RequestUtils.requesRecharge(context, MyRechargeTask.GATEWAY.weixin,amount);
        }
    }
}
